package com.design.marketPrj.application.service;


import com.alibaba.fastjson.JSONObject;
import com.design.marketPrj.application.bean.PO.Storage;
import com.design.marketPrj.application.bean.PO.StorageExample;
import com.design.marketPrj.application.bean.PO.User;
import com.design.marketPrj.application.mapper.StorageMapper;
import com.design.marketPrj.application.mapper.UserMapper;
import com.design.marketPrj.application.util.DateUtil;
import com.design.marketPrj.application.util.UUIDUtils;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

@Service
public class TradeService{
    @Autowired
    UserMapper userMapper;
    @Autowired
    StorageMapper storageMapper;
    @Autowired
    ExcludeDataService excludeDataService;


    @Transactional(rollbackFor = Exception.class)
    public JSONObject buy(String code,String moneyToBuy,User user){
        JSONObject jsonObject = new JSONObject();
        BigDecimal money = new BigDecimal(moneyToBuy);
        if(user.getMoney().compareTo(money)<0?true:false){
            jsonObject.put("code",500);
            jsonObject.put("msg","余额不足!");
            return jsonObject;
        }
        else
        {
            //若余额充足则扣钱
            user.setMoney(user.getMoney().subtract(money));
            userMapper.updateByPrimaryKeySelective(user);
            //查询该用户下是否已有该类型产品
            StorageExample storageExample = new StorageExample();
            storageExample.or().andProductCodeEqualTo(code).andUserIdEqualTo(user.getId());
            List<Storage> storageList = storageMapper.selectByExample(storageExample);
            //调用api查询当日的产品净值
            JSONObject productDetail = excludeDataService.getProductDetail(code,DateUtil.getDate());
            BigDecimal netWorth = (BigDecimal)productDetail.get("netWorth");
            String name = (String) productDetail.get("name");
            //如果已存在该产品，则在原记录上改动，增加份数的计算公式为金额/单位净值
            if(storageList.size()>0){
                Storage storage = storageList.get(0);
                BigDecimal orginAmount = storage.getAmount();
                storage.setAmount(orginAmount.add(money.divide(netWorth, 4, BigDecimal.ROUND_HALF_UP)));
                storageMapper.updateByPrimaryKey(storage);
            }
            else {
                Storage storage = new Storage();
                storage.setAmount(money.divide(netWorth, 4, BigDecimal.ROUND_HALF_UP));
                storage.setId(UUIDUtils.getUUID());
                storage.setProductCode(code);
                storage.setUserId(user.getId());
                storage.setProductName(name);
                storageMapper.insert(storage);
            }
            jsonObject.put("code",200);
            jsonObject.put("msg","购买成功!");
        }
        return jsonObject;
    }

    @Transactional(rollbackFor = Exception.class)
    public JSONObject sell(String code,String amountToSell,User user){
        JSONObject jsonObject = new JSONObject();
            if(amountToSell.equals("0")){
            jsonObject.put("code",500);
            jsonObject.put("msg","出售失败，出售份数不可为0!");
            return jsonObject;
        }
        BigDecimal amount = new BigDecimal(amountToSell);
        StorageExample storageExample = new StorageExample();
        storageExample.or().andProductCodeEqualTo(code).andUserIdEqualTo(user.getId());
        List<Storage> storageList = storageMapper.selectByExample(storageExample);
        BigDecimal netWorth = (BigDecimal)excludeDataService.getProductDetail(code,DateUtil.getDate()).get("netWorth");
        if(storageList.size()>0)
        {
            Storage storage = storageList.get(0);
            BigDecimal orginAmount = storage.getAmount();
            //若出售份数小于等于库存份数
            if(storage.getAmount().compareTo(amount)!=-1){
                storage.setAmount(orginAmount.subtract(amount).setScale(4,BigDecimal.ROUND_HALF_UP));
                storageMapper.updateByPrimaryKey(storage);
                //账户加钱，计算用户的当日净值*出售份额所能获得的金钱
                user.setMoney(user.getMoney().add(amount.multiply(netWorth).setScale(2,BigDecimal.ROUND_HALF_UP)));
                userMapper.updateByPrimaryKeySelective(user);
                jsonObject.put("code",200);
                jsonObject.put("msg","出售成功!");
                return jsonObject;
            }
            else {
                jsonObject.put("code",500);
                jsonObject.put("msg","出售失败，出售份数不得大于持有份数!");
                return jsonObject;
            }
        }
        else {
            jsonObject.put("code",500);
            jsonObject.put("msg","出售失败，请确定您的库存下有该商品!");
            return jsonObject;
        }
    }

}
